import pageJson from "@/pages.json";
import { ingorePage } from "./ignorePage";
import { userStore } from "@/store/userStore";
var env = import.meta.env
export const tip = function (title : string, fun ?: Function, delay = 1000) {
	//普通提示
	uni.showToast({
		title: String(title),
		icon: "none",
		delay,
	});
	if (typeof fun == "function") {
		setTimeout(function () {
			fun();
		}, delay);
	}
};

export const goback = function () {
	//返回
	if (isFirst()) {
		goto(pageJson.pages[0].path, "tab"); //pages里的第一个页面
	} else {
		uni.navigateBack();
	}
};
export const isFirst = () => {
	//打开的第一个页面
	let pages = getCurrentPages();
	if (pages.length == 1) {
		return true;
	} else {
		return false;
	}
};

export const loading = function (title ?: string) {
	//加载中
	uni.showLoading({
		title: title ? title : "正在加载",
		mask: true,
	});
};
export const hideloading = function () {
	uni.hideLoading();
};
export const needLoginPage = (page : string) => {
	if (ingorePage.indexOf(page) >= 0) {
		//忽略判断的页面
		return false;
	}
	const user = userStore();
	if (!user.isLogin) {
		user.logout();
		return true;
	} else {
		return false;
	}
};
//跳转页面
export const goto = function (url : string, type = "navigateTo", params = {}) {
	//如果url最前面不是'/'，则补上
	if (url.indexOf("/") != 0) {
		url = "/" + url;
	}
	uni.$uv.route({
		url: url,
		type: type,
		params: params,
		intercept({ }, next : any) {
			//路由拦截
			if (needLoginPage(url)) {
				goLogin({
					back: url,
					type: type,
					params: params,
				});
				next(false);
			} else {
				next(true);
			}
		},
	});
};
export const goLogin = (param ?: any) => {
	goto("/pages/user/login", "to", param);
};
//富文本替换
export const richtxt = function (content : string) {
	const regex = /<img([^>]*)>/gi;
	content = content.replace(regex, (match, attributes) => {
		if (attributes.includes("style=")) {
			return match.replace(
				/style=[\'"][^\'"]*[\'"]/gi,
				'style="max-width: 100%;display:block"'
			);
		} else {
			return match.replace(
				"<img",
				'<img style="max-width: 100%;display:block"'
			);
		}
	});
	return content;
};

//显示textarea的换行
export const textareaCon = (str:string)=>{
	str = str.split('\n').map(line => `<p>${line}</p>`).join('');
	return str
}

export const copy = function (
	con : string,
	tipStr = "复制成功",
	callback ?: Function
) {
	uni.setClipboardData({
		data: con,
		showToast: tipStr != "",
		success() {
			if (tipStr != "") {
				tip(tipStr);
			}
			if (typeof callback == "function") {
				callback();
			}
		},
		fail: (err : any) => {
			console.log(err);
			tip("复制失败");
		},
	});
};

export const confirm = function (
	opt : object | string,
	done ?: Function,
	reject ?: Function
) {
	let option = {
		title: "提示",
		content: "",
		success(res : any) {
			if (res.confirm) {
				if (typeof done == "function") {
					done();
				}
			} else {
				if (typeof reject == "function") {
					reject();
				}
			}
		},
	};
	if (typeof opt == "object") {
		Object.assign(option, opt);
	} else if (typeof opt == "string") {
		option.content = opt;
	}
	uni.showModal(option);
};
//下载图片
export const downImg = function (file_url : string) {
	loading("正在保存");
	uni.downloadFile({
		//下载图片
		url: file_url,
		filePath: "",
		success(res : any) {
			uni.saveImageToPhotosAlbum({
				filePath: res.tempFilePath,
				success() {
					hideloading();
					tip("保存成功！");
				},
				fail(err : any) {
					console.log(err);
					hideloading();
					tip("保存失败:" + err.errMsg);
				},
			});
		},
		fail() {
			hideloading();
			tip("保存失败");
		},
	});
};

//下载文件
export const downVideo = function (video_url : string) {
	loading("正在保存");
	uni.downloadFile({
		//下载图片
		url: video_url,
		filePath: "",
		success(res : any) {
			uni.saveVideoToPhotosAlbum({
				filePath: res.tempFilePath,
				success() {
					hideloading();
					tip("保存成功！");
				},
				fail(err : any) {
					console.log(err);
					hideloading();
					tip("保存失败");
				},
			});
		},
		fail() {
			hideloading();
			tip("保存失败");
		},
	});
};
//脱敏
export const maskString = (str:string, start:number, length:number)=>{
	let end = start + length
	if(end > str.length){
		end = str.length
	}
    if (start >= end || start < 0) {
        return str;
    }
    const maskedPart = '*'.repeat(end - start);
    return str.slice(0, start) + maskedPart + str.slice(end);
}

export const getImg = (file_path:string)=>{
	if(!file_path){
		return ""
	}
	if(file_path.includes("https")){
		return file_path
	}
	else{
		return env.VITE_IMG_URL + file_path
	}
}

//保存64位图片
export const saveBase64 = (base64File:string)=>{
	// 去掉 Base64 数据的前缀
	const base64Data = base64File.replace(/^data:image\/\w+;base64,/, '');

	// 获取文件系统管理器
	const fs = uni.getFileSystemManager();
	const tempFilePath = `${uni.env.USER_DATA_PATH}/temp_qrcode.png`;

	// 将 Base64 数据写入临时文件
	fs.writeFile({
		filePath: tempFilePath,
		data: base64Data,
		encoding: 'base64',
		success: () => {
			// 保存图片到相册
			uni.saveImageToPhotosAlbum({
				filePath: tempFilePath,
				success: () => {
					uni.showToast({
						title: '保存成功',
						icon: 'success'
					});
				},
				fail: (err) => {
					console.error('保存失败', err);
					uni.showToast({
						title: '保存失败',
						icon: 'none'
					});
				}
			});
		},
		fail: (err) => {
			console.error('写入文件失败', err);
			uni.showToast({
				title: '写入文件失败',
				icon: 'none'
			});
		}
	});
}